package com.yzqp.sys.service;

import com.yzqp.common.mvc.base.BaseService;
import org.springframework.stereotype.Service;
import com.yzqp.sys.bean.*;
import com.yzqp.sys.mapper.*;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Permission service
 */
@Service
public class PermissionService extends BaseService<PermissionMapper, PermissionBean> {


    /**
     * 查找全部的权限集合(多级集合)
     * @return
     */
    public List<PermissionBean> findAllPermissionListByTree(){
        // 全部集合
        List<PermissionBean> allList = super.findAllList();
        // 全部集合
        List<PermissionBean> forAllList = super.findAllList();
        // 树集合
        List<PermissionBean> treeList = new ArrayList<>();
        // 循环根节点
        for(PermissionBean item : forAllList){
            if(0 == item.getParentId()){
                // 设置子节点(循环设置子节点)
                this.setChildList(item, allList);
                treeList.add(item);
            }
        }
        return treeList;
    }

    /**
     * 设置子权限集合
     * @param root
     * @param allList
     */
    public void setChildList(PermissionBean root, List<PermissionBean> allList){
        // 添加子节点
        for(int i = 0 ; i < allList.size() ; i ++){
            PermissionBean item = allList.get(i);
            // 判断项的父id == 根id
            if(root.getId() == (int)item.getParentId()){
                if(root.getChildList() == null){
                    root.setChildList(new ArrayList<>());
                }
                root.getChildList().add(item);
                // 删除这个项
//                allList.remove(i);
//                i --;
            }
        }
        // 子节点循环添加
        if(root.getChildList() != null) {
            root.setChildFlag(true);
            for (int i = 0; i < root.getChildList().size(); i++) {
                this.setChildList(root.getChildList().get(i), allList);
            }
        }else {
            root.setChildFlag(false);
        }
    }
}
